package ro.upt.dcda.web;

import java.net.InetAddress;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import ro.upt.dcda.pricezone.s1.requests.LoginRequest;

import com.maxmind.geoip2.model.CityResponse;
import com.opensymphony.xwork2.ActionContext;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet {

	private String usermail;
	private String password;

	public String execute() throws Exception {
		try {
			LoginRequest loginRequest = new LoginRequest();
			System.out.println("Logging user");
			if (loginRequest.work(usermail, password, 0)) {
				System.out.println("Loggin sucessful with sid:"
						+ loginRequest.getSid());
				Map<String, Object> session = ActionContext.getContext()
						.getSession();
				session.put("user", loginRequest.getUser());
				session.put("email", loginRequest.getUser().getEmail());
				session.put("sid", loginRequest.getSid());
				HttpServletRequest request = ServletActionContext.getRequest();
				CityResponse response = LocationReader.getLocation(InetAddress
						.getByName(request.getRemoteAddr()));
				if (response != null) {
					session.put("location",
							LocationReader.locationToString(response));
					session.put("city", response.getCity().getName());
					session.put("longitude", response.getLocation()
							.getLongitude());
					session.put("latitude", response.getLocation()
							.getLatitude());
				} else {
					session.put("location", "unknown");
					session.put("city", "unknown");
					session.put("longitude", 0);
					session.put("latitude", 0);
				}
				return "success";
			} else {
				return "failed";
			}
		} catch (Exception ex) {
			ex.printStackTrace(System.out);
			return "failed";
		}
	}

	public String getUsermail() {
		return usermail;
	}

	public void setUsermail(String usermail) {
		this.usermail = usermail;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
}
